package cn.ddiancan.xddcloud.common.context;

import lombok.Getter;
import org.springframework.http.HttpHeaders;
import org.springframework.util.MultiValueMap;

import java.io.Closeable;

/**
 * 上下文容器，用来储存上下文内容，并进行线程隔离
 *
 * @author Amos
 */
public class CloudRequestContext implements Closeable {

    private static final ThreadLocal<CloudRequestContext> requestVariables = new ThreadLocal<>();

    @Getter
    private MultiValueMap<String, String> outGoing = new HttpHeaders();

    @Getter
    private MultiValueMap<String, String> inComing = new HttpHeaders();

    /**
     * 判断是否初始化
     *
     * @return
     */
    public static boolean isCurrentThreadInitialized() {
        CloudRequestContext context = requestVariables.get();
        return context != null;
    }

    /**
     * 当前线程中获取容器
     *
     * @return
     */
    public static CloudRequestContext getContextForCurrentThread() {
        CloudRequestContext context = requestVariables.get();
        if (context != null) {

            return context;
        } else {
            return null;
        }
    }

    /**
     * 设置容器
     *
     * @param state
     */
    public static void setContextOnCurrentThread(CloudRequestContext state) {
        requestVariables.set(state);
    }

    /**
     * 初始化
     *
     * @return
     */
    public static CloudRequestContext initializeContext() {
        CloudRequestContext state = new CloudRequestContext();
        setContextOnCurrentThread(state);
        return state;
    }

    /**
     * 关闭，清理threadlocal
     */
    public void shutdown() {
        requestVariables.remove();
        inComing.clear();
        outGoing.clear();
    }

    public void close() {
        shutdown();
    }
}
